import pool from '../config/database';
export interface dictType {
  id?: number;
  type_code: string;
  type_name: string;
  remark: string;
  create_by?: string;
  update_by?: string;
}
export class DictTypeModel {
  async create(dictType: dictType): Promise<any> {
    const { type_code, type_name, remark, create_by, update_by } = dictType;
    const sql = `insert into sys_dict_type(type_code, type_name, remark, create_by, update_by) values('${type_code}', '${type_name}', '${remark}', '${create_by}', '${update_by}')`;
    const [result] = await pool.execute(sql)
    return result;
  }
  async update(dictType: dictType): Promise<any> {
    const { type_code, type_name, remark, update_by, id } = dictType;
    const sql = `update sys_dict_type set type_code = '${type_code}', type_name = '${type_name}', remark = '${remark}', update_by = '${update_by}' where id = ${id}`;
    const [result] = await pool.execute(sql)
    return result;
  }
  async delete(ids: number[], userId?: string): Promise<any> {
    let sql = `update sys_dict_type set is_deleted = 1  where id IN (${ids.join(',')})`
    if (userId) {
      sql = `update sys_dict_type set is_deleted = 1  where id IN (${ids.join(',')}) and create_by = '${userId}'`;
    }
    const [result] = await pool.execute(sql)
    return result;
  }
  async getDictTypeList(pageNum: number, pageSize: number): Promise<any> {
    const sql = `select * from sys_dict_type where is_deleted = 0 ORDER BY create_time DESC limit ${pageSize} OFFSET ${(pageNum - 1) * pageSize}`;
    const [rows] = await pool.execute(sql)
    const [totalRows] = await pool.execute(
      'SELECT COUNT(*) AS total FROM sys_dict_type where is_deleted = 0'
    );
    return {
      rows,
      total: (totalRows as any)[0].total
    };
  }
  async findByCode(code: string): Promise<any> {
    const sql = `select * from sys_dict_type where type_code = '${code}'`;
    const [rows] = await pool.execute(sql)
    return rows;
  }
  async findById(id: number): Promise<any> {
    const sql = `select * from sys_dict_type where id = ${id}`;
    const [rows] = await pool.execute(sql)
    return rows;
  }
  async findByCodes(codes: string[]): Promise<any> {
    const sql = `select * from sys_dict_type where type_code in ('${codes.join("','")}')`;
    const [rows] = await pool.execute(sql)
    return rows;
  }
}